package com.init;

import io.github.xdiamond.client.XDiamondConfig;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.springframework.web.context.ContextLoaderListener;

import com.orangelife.utils.StringUtils;

public class InitSpring extends ContextLoaderListener {

	/***
	 * 初始化配置的map
	 */
	public static Map<String, Object> propMap = new HashMap<String, Object>();

	public InitSpring() {
		/***
		 * 
		 */
		OutputStream sysOut = null;

		InputStream sysInputStream = null;

		try {

			// Map<String, String> map = System.getenv();
			// Properties properties = // System.getProperties();
			/**
			 * 从环境变量获取配置中心的配置信息
			 */

			String serverHost = System.getenv("CONFIG_CONN");
			if (StringUtils.isBlank(serverHost)) {
				throw new Exception("亲，配置文件链接地址的的环境变量未配置");
			}
			String configKey = System.getenv("CONFIG_KEY");
			if (StringUtils.isBlank(configKey)) {
				throw new Exception("亲，配置文件秘钥的的环境变量未配置");
			}
			String serviceName = System.getenv("SERVICE_NAME");
			if (StringUtils.isBlank(serviceName)) {
				throw new Exception("亲，配置文件服務名稱的的环境变量未配置");
			}
			/**
			 * 获取版本号
			 */
			String version = System.getenv("SERVICE_VERSION");
			if (StringUtils.isBlank(version)) {
				version = "LTS";
			}
			/**
			 * 获取配置文件名称
			 */
			String profile = System.getenv("PROFILE");
			if (StringUtils.isBlank(profile)) {
				throw new Exception("亲，配置文件名稱的的环境变量未配置");
			}
			/**
			 * 获取请求地址
			 */

			String secretKey = configKey;
			int port = 5678;

			/**
			 * 配置 公司表头
			 */
			String groupId = serviceName.substring(0,
					StringUtils.getUpIndex(serviceName) - 1); // "orange.core";

			/**
			 * 获取项目名称
			 */
			String artifactId = serviceName.substring(
					StringUtils.getUpIndex(serviceName), serviceName.length()); // "PayCenter";

			XDiamondConfig config = new XDiamondConfig(serverHost, port,
					groupId, artifactId, version, profile, secretKey);
			config.setRetryIntervalSeconds(2);
			config.setMaxRetryIntervalSeconds(10);
			config.setMaxRetryTimes(0);
			config.init();

			/***
			 * 创建systems.properties 配置文件
			 */
			String basePath = getClass().getResource("/").getPath()
					.replaceAll("%20", " ");
			String systemProPath = basePath + "/system.properties";
			File systemFiles = new File(systemProPath);
			if (!systemFiles.exists()) {
				systemFiles.createNewFile();
			}
			sysInputStream = new BufferedInputStream(new FileInputStream(
					systemFiles));
			Properties sysProp = new Properties();
			sysProp.load(sysInputStream); // /加载属性列表

			/**
			 * 获取基础通用的配置
			 */
			Properties baseProperties = config.getProperties();
			Iterator<Entry<Object, Object>> baseIt = baseProperties.entrySet()
					.iterator();
			while (baseIt.hasNext()) {
				Entry<Object, Object> entry = baseIt.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				propMap.put((String) key, value);
				sysProp.setProperty((String) key, (String) value);

			}

			URI dbUri = new URI(config.getProperty("DB_CONN") + "");

			if (StringUtils.isBlank(config.getProperty("DB_CONN"))) {
				throw new Exception("亲，数据库的相关配置未填写");
			}
			String s = new String(dbUri.getUserInfo());
			String a[] = s.split(":");
			String username = a[0];
			String password = a[1];
			String url = null;
			if ("mysql".equals(dbUri.getScheme().toLowerCase())) {
				url = "jdbc:mysql://"
						+ dbUri.getHost()
						+ ":"
						+ dbUri.getPort()
						+ dbUri.getPath()
						+ "?autoReconnect=true&useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8";
			}

			sysProp.setProperty("jdbc.url", url);
			sysProp.setProperty("jdbc.username", username);
			sysProp.setProperty("jdbc.password", password);

			sysOut = new BufferedOutputStream(new FileOutputStream(new File(
					systemProPath)));
			sysProp.store(sysOut, "更新系统配置");

			if (StringUtils.isBlank(config.getProperty("jdbc.driver"))) {
				throw new Exception("亲，数据库的相关配置未填写");
			}

			sysInputStream.close();

			config.destory();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			/**
			 * 关闭文件读取流
			 */
			try {

				if (sysInputStream != null) {
					sysInputStream.close();
				}

				if (sysOut != null) {
					sysOut.close();
				}

			} catch (IOException e) {

			}

		}

		/***
		 * 获取环境变量
		 */

	}

	public static Map<String, Object> getPropMap() {
		return propMap;
	}

	public static void setPropMap(Map<String, Object> propMap) {
		InitSpring.propMap = propMap;
	}
}
